/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.graphicals;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JLabel;

/**
 *
 * @author thomas
 */
public class BannerLabel extends JLabel {

    private final static String __SPACE = " ";
    private String _text;
    private int _bufferSize;
    private int _position;
    private boolean _isReading = false;
    private Thread _thread;

    public BannerLabel(String text, int bufferSize) {
        super();

        _text = text;
        _bufferSize = bufferSize;
        _position = 0;

        setBorder(BorderFactory.createEtchedBorder());

        _thread = new Thread() {

            @Override
            public void run() {
                while (true) {

                    if (!_isReading) {
                        synchronized (_thread) {
                            try {
                                _thread.wait();
                            } catch (InterruptedException ex) {
                                Logger.getLogger(BannerLabel.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }

                    moving();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(BannerLabel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };
        _thread.start();
    }

    public void setAnotherText(String text) {
        _text = text;
    }

    public void moving() {
        if (_position++ > _bufferSize + _text.length()) {
            _position = 0;
        }
        draw();
    }

    private void draw() {
        
        int init = 0;
        if (_bufferSize - _position < 0) {
            init = Math.min(_position - _bufferSize, _text.length());
        }
        String debut = _text.substring(init, Math.min(_position, _text.length()));
        setText(spaces(Math.max(0, _bufferSize - _position)) + debut);
        repaint();
    }

    private static String spaces(int nb) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < nb; i++) {
            sb.append(__SPACE);
        }
        return sb.toString();
    }

    public void start() {
        _isReading = true;
        synchronized (_thread) {
            _thread.notify();
        }
    }

    public void stop() {
        _isReading = false;
    }
}
